package com.ding.dao.impl;


import com.ding.dao.UserRepository;
import com.ding.pojo.User;
import javassist.NotFoundException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class UserRepositoryImpl implements UserRepository {

	private SessionFactory factory;

	@Autowired
	public UserRepositoryImpl(SessionFactory factory){
		this.factory=factory;
	}

	private Session session() {
		return factory.getCurrentSession();//Session是保存在当前线程中的,必须开启事务,才能获取该Session
	}

	@Transactional
	@Override
	public void save(User user) {
		session().persist(user);
	}

	@Transactional
	@Override
	public void delete(String username) throws NotFoundException {
		User user = query(username);
		if (user==null) {
			throw new NotFoundException("没有找到账户"+username);
		}
		session().delete(user);
	}

	@Transactional
	@Override
	public void update(User user) throws NotFoundException {
		if (query(user.getUsername())==null) {
			throw new NotFoundException("没有找到账户"+user.getUsername());
		}
		session().merge(user);
	}

	@Override
	public User query(String username) {
		Session session = factory.openSession(); //手动开启/关闭Session
		return session.get(User.class, username);
	}

}
